import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import FormInput from '../components/FormInput';
import SubmitButton from '../components/SubmitButton';
import { login } from '../services/api';

const Login: React.FC = () => {
    const navigate = useNavigate();
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    const handleLogin = async () => {
        try {
            const response = await login(username, password);
            localStorage.setItem('token', response.data.token);
            window.location.href = `http://180.76.147.158:3090/?redirect_uri=${encodeURIComponent("http://10.55.2.62:5173/")}&token=${response.data.token}`
                } catch (err: any) {
            setError(err.response?.data?.error || '登录失败');
        }
    };

    return (
        <div className="auth-container">
            <h2>IAM统一登录平台</h2>
            <p>请输入您的账号信息进行登录</p>
            {error && <p className="error">{error}</p>}
            <FormInput label="用户名" placeholder="请输入用户名" value={username} onChange={(e) => setUsername(e.target.value)} />
            <FormInput label="密码" placeholder="请输入密码" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
            <SubmitButton text="登录" onClick={handleLogin} />
            <div className="links">
                <a href="#" onClick={() => navigate('/forgot-password')}>忘记密码?</a>
                <a href="#" onClick={() => navigate('/update-password')}>修改密码</a>
            </div>
            <p>还没有账号？<a href="#" onClick={() => navigate('/register')}>立即注册</a></p>
        </div>
    );
};

export default Login;